<script lang="ts">
  export default {
    name: 'PoleTalkContainer',
  };
</script>
<script setup lang="ts">
  import { computed, ref, onBeforeUnmount, watch } from 'vue';
  import { useResizeObserver } from '@vueuse/core';

  interface TalkContainerProps {
    /** 最大高度 */
    maxHeight?: number;
    /** 默认是否展开 */
    showAll?: boolean;
    /** 当不支持容器监听特性时是否需要展开 */
    ifNotSupportedWillNeed?: boolean;
  }
  const props = withDefaults(defineProps<TalkContainerProps>(), {
    maxHeight: 155,
    showAll: false,
    ifNotSupportedWillNeed: true,
  });
  const emit = defineEmits(['update:showAll']);

  const contentRef = ref();
  const contentHeightRef = ref<number>();

  // 默认需要支持展开
  const isNeedShowAllRef = computed(() => {
    return typeof contentHeightRef.value !== 'undefined'
      ? contentHeightRef.value >= props.maxHeight
      : props.ifNotSupportedWillNeed;
  });

  // 是否展开
  const isShowAllRef = ref(false);
  watch(
    () => props.showAll,
    () => {
      isShowAllRef.value = !!props.showAll;
    },
    { immediate: true },
  );
  watch(isShowAllRef, () => {
    emit('update:showAll', isShowAllRef.value);
  });

  // 容器最大高度
  const getContentStyle = computed(() => {
    return {
      maxHeight: isNeedShowAllRef.value
        ? isShowAllRef.value
          ? 'none'
          : `${props.maxHeight}px`
        : undefined,
    };
  });

  // 展开文案
  const getShowAllText = computed(() => {
    return isNeedShowAllRef.value ? (isShowAllRef.value ? '收起' : '展开全部') : '';
  });

  // 点击展开
  const onShowAll = () => {
    isShowAllRef.value = !isShowAllRef.value;
  };

  // 容器尺寸监听
  const callback: ResizeObserverCallback = (entries) => {
    contentHeightRef.value = entries[0]?.contentRect.height;
  };
  const { isSupported, stop } = useResizeObserver(contentRef, callback);
  onBeforeUnmount(() => {
    if (isSupported.value) {
      stop();
    }
  });
</script>

<template>
  <div>
    <div :style="getContentStyle" class="overflow-hidden" ref="contentRef">
      <slot></slot>
    </div>
    <div class="mt-[10px] text-[14px] cursor-pointer" @click="onShowAll" v-if="isNeedShowAllRef">
      <slot name="text" :isShowAll="isShowAllRef">{{ getShowAllText }}</slot>
    </div>
  </div>
</template>
